package com.token.iot.bratterycharging.gateway.oper;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.TransactionContext;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.AbstractOper;
import com.token.iot.bratterycharging.gateway.IMEI;
import com.token.iot.bratterycharging.gateway.Oper;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.api.Ping;
import com.token.iot.bratterycharging.gateway.dao.PingDAO;
import com.token.iot.bratterycharging.gateway.dao.TableDMLDAO;
import com.token.iot.bratterycharging.gateway.server.BratteryChargingServerHandler;
import com.token.iot.bratterycharging.gateway.server.OperService;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;
import com.token.iot.bratterycharging.gateway.utils.ChannelHandlerContextUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

/**
 * 响应ping
 * 
 * @author chenzhixuan
 *
 */
@Component("AXTOper")
public class AXTOper extends AbstractOper {

	private static Logger loger = LoggerFactory.getLogger(AXTOper.class);

	@Autowired
	private PingDAO dao;

	@Autowired
	private TableDMLDAO tableDao;

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

	@Override
	public int onCall(byte[] b, ChannelHandlerContext ctx) throws PendingException {
		String val = new String(b);
		Date d = new Date();
		Ping p = Ping.build(val);
		p.setYmd(sdf.format(d));
		String imei = null;
		try {
			imei = IMEI.getIMEI(ctx);
			p.setImei(imei);
			String ip = ChannelHandlerContextUtil.getIP(ctx);
			p.setIp(ip);

		} catch (Exception e) {
			// 如果imei为空，则应该尽快发送
			String getDevice = "ADV000000/IMEI";
			byte[] bb = getDevice.getBytes();
			byte[] c = ByteUtil.addFlag(bb);
			loger.debug("on ping Get imei command has been reSended" + new String(c));
			ctx.writeAndFlush(c);
		}

		String tableName = "Pings" + p.getYmd();
		String name = tableDao.isTargetTableExistInDB(tableName);
		if (StringUtils.isBlank(name)) {
			try {
				tableDao.copyTable(tableName, "Pings");
				
			} catch (Exception e) {
				loger.error(e);
			}
		}
		try {
			dao.insert(p);
		} catch (Exception e) {
			loger.error(e);
		}

		// 需要回应心跳
		if (imei == null) {
			loger.info("put the context into the Transaction " + String.valueOf(ctx == null));
			TransactionContext.putData(Constant.CHANNELCONTEXT, ctx);
		}
		return 1;
		// loger.info(" the ping signalType=" + signalType);

	}

}